//
//  MainViewController.m
//  iMiniTao
//
//  Created by liunian on 13-8-14.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "MainViewController.h"
#import "MKNavigationController.h"
#import <QuartzCore/QuartzCore.h>
#import "SourceView.h"
#import "OptionViewController.h"
#import "FavoritesController.h"
#import "SearchViewController.h"
#import "UMSocial.h"
#import "CoverView.h"

#define kDefaultAnimationIntervalSlow     1.0f
#define kDefaultAnimationIntervalMedium   0.5f
#define kDefaultAnimationIntervalFast     0.3f
#define kDefaultAnimationIntervalFaster   0.2f

@interface MainViewController ()<UIGestureRecognizerDelegate,SourceViewDelegate,UMSocialUIDelegate,ApplicationManagerDelegate>{
    CGRect          _orignFrame;
}
@property (nonatomic, retain) UIPanGestureRecognizer *panGesture;
@property (nonatomic, retain) UIImageView       *bgImageView;
@property (nonatomic, strong) CoverView *coverView;
@property (nonatomic, retain) SourceView *sourceView;
@end

@implementation MainViewController

- (id)init {
    self = [super init];
    if (self) {
        [DataEnvironment sharedDataEnvironment].mainViewController = self;
        
        self.view.backgroundColor = COLOR_RGB(248, 248, 248);
        self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
        [self.panGesture setMaximumNumberOfTouches:2];
        self.panGesture.delegate = self;
        [self.view addGestureRecognizer:self.panGesture];
        
        self.slideEnabled = YES;
        [[ApplicationManager sharedManager] addObserver:self];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleAppDidEnterBackground:)
                                                     name:UIApplicationDidEnterBackgroundNotification
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleAppWillEnterForeground:)
                                                     name:UIApplicationWillEnterForegroundNotification
                                                   object:nil];
        
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.view addSubview:self.bgImageView];
    [self initBackground];
    [self sourceView];
    [self.view addSubview:self.coverView];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [DataEnvironment sharedDataEnvironment].isMainViewPresentingController = NO;
    self.mainViewShown = YES;
//启动推荐位动画
    if (!self.coverView.superview) {
        [self.sourceView sourceViewDidAppear];
    }
    
    [MobClick beginLogPageView:@"主页"];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    self.mainViewShown = NO;
    //停止推荐位动画
    if (!self.coverView.superview) {
        [self.sourceView sourceviewWillDisappear];
    }
    [MobClick endLogPageView:@"主页"];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    self.sourceView = nil;
    // Dispose of any resources that can be recreated.
}


- (void)initBackground{
    
    if ([[ApplicationManager sharedManager] backgroundImage]) {
        [self.bgImageView setImage:IMGNAMED([[ApplicationManager sharedManager] backgroundImage])];
    }else{
        NSInteger i = arc4random() % 14;
        NSString *imageName = [NSString stringWithFormat:@"bg_source_%d.jpg",i];
        
        UIImage *image_bg = nil;
        image_bg = IMGNAMED(imageName);
        [self.bgImageView setImage:image_bg];
    }
}
#pragma mark ApplicationManagerDelegate
- (void)mkManagerDesktopBackgroundImageChanged:(NSString *)imageName{
    [self initBackground];
}

#pragma mark SourceViewDelegate
- (void)setting;{
    [DataEnvironment sharedDataEnvironment].isMainViewPresentingController = YES;
    OptionViewController   *viewController = [[OptionViewController alloc] init];
    UINavigationController  *nav = [[UINavigationController alloc] initWithRootViewController:viewController];
    nav.navigationBarHidden = YES;
    [self.navigationController presentViewController:nav animated:YES completion:^{
        
    }];
}
- (void)favorit{
    [DataEnvironment sharedDataEnvironment].isMainViewPresentingController = YES;
    FavoritesController   *viewController = [[FavoritesController alloc] init];
    UINavigationController  *nav = [[UINavigationController alloc] initWithRootViewController:viewController];
    nav.navigationBarHidden = YES;
    [self.navigationController presentViewController:nav animated:YES completion:^{
        
    }];
}
- (void)search{
    [DataEnvironment sharedDataEnvironment].isMainViewPresentingController = YES;
    SearchViewController   *viewController = [[SearchViewController alloc] init];
    UINavigationController  *nav = [[UINavigationController alloc] initWithRootViewController:viewController];
    nav.navigationBarHidden = YES;
    [self.navigationController presentViewController:nav animated:YES completion:^{
        
    }];
}
- (void)forward{
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:kUmengAppKey
                                      shareText:@"正品汇-京东特选"
                                     shareImage:IMGFROMBUNDLE(@"Icon.png")
                                shareToSnsNames:nil
                                       delegate:self];
}
#pragma mark UMSocialUIDelegate
-(void)didSelectSocialPlatform:(NSString *)platformName withSocialData:(UMSocialData *)socialData{
    socialData.shareText = [NSString stringWithFormat:@"%@[%@]..",socialData.shareText,kLinkItunes];
    
    if (platformName == UMShareToWechatSession) {
        [UMSocialData defaultData].extConfig.title = @"正品汇-京东特选";   //分享标题，分享到朋友圈只能显示标题内容
        [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeOther; //设置为网页、音乐等其他类型
        WXAppExtendObject *appObject = [WXAppExtendObject object];    //初始化微信网页对象
        appObject.url = kLinkItunes;
        [UMSocialData defaultData].extConfig.wxMediaObject = appObject; //设置网页对象
    }
}
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response{
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          [Util stringWithDate:[NSDate date]], @"shareTime", nil];
    [MobClick event:@"ShareApp" attributes:dict];
}



#pragma mark - handle notifications
- (void)handleAppDidEnterBackground:(NSNotification *)notification {
    [self showCover];
    if (self.coverView.superview) {
        [self.coverView stopImageSwitch];
    }
}

- (void)handleAppWillEnterForeground:(NSNotification *)notifcation {
    self.slideEnabled = YES;
    if (self.coverView.superview) {
        [self.coverView startImageSwitch];
    }
}
- (void)setSlideEnabled:(BOOL)slideEnabled {
    _slideEnabled = slideEnabled;
    self.panGesture.enabled = _slideEnabled;
}
#pragma mark - Utility
static inline UIViewAnimationOptions animationOptionsWithCurve(UIViewAnimationCurve curve)
{
    switch (curve) {
        case UIViewAnimationCurveEaseInOut:
            return UIViewAnimationOptionCurveEaseInOut;
        case UIViewAnimationCurveEaseIn:
            return UIViewAnimationOptionCurveEaseIn;
        case UIViewAnimationCurveEaseOut:
            return UIViewAnimationOptionCurveEaseOut;
        case UIViewAnimationCurveLinear:
            return UIViewAnimationOptionCurveLinear;
    }
}

- (void)hideCover {
    if (_coverView && _coverView.superview) {
        [self.coverView stopImageSwitch];
        
        CGRect frame = _coverView.frame;
        frame.origin.x = -frame.size.width;
        
        [UIView animateWithDuration:kDefaultAnimationIntervalFast
                              delay:0.5
                            options:animationOptionsWithCurve(UIViewAnimationCurveEaseInOut)
                         animations:^{
                             _coverView.frame = frame;
                         }
                         completion:^(BOOL finished) {
                             [_coverView removeFromSuperview];
                         }];
    }
}
- (void)showCover {
    if (!self.coverView.superview) {
        [self.view addSubview:self.coverView];
        
    }
    [self.coverView setFrame:self.view.bounds];
}

#pragma mark - UIGestureRecognizer handler method
- (void)pan:(UIPanGestureRecognizer *)gestureRecognizer {
    if (self.sourceView.currentPage > 0  && !self.coverView.superview) {
        return;
    }
    
    static BOOL initialized = NO;
    UIView *view = self.coverView;
    
    CGPoint translation = [gestureRecognizer translationInView:self.view];
    
    if ((view.frame.origin.x >= 0 && translation.x > 0) ||
        (view.frame.origin.x <= -self.view.bounds.size.width && translation.x < 0)) {
        if (gestureRecognizer.state != UIGestureRecognizerStateEnded &&
            gestureRecognizer.state != UIGestureRecognizerStateRecognized &&
            gestureRecognizer.state != UIGestureRecognizerStateCancelled &&
            gestureRecognizer.state != UIGestureRecognizerStateFailed)
            {
            return;
            } else {
                if (!initialized) {
                    return;
                }
            }
    }
    
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        
        if (!self.coverView.superview) {
            [self.sourceView sourceviewWillDisappear];
            [self.view addSubview:self.coverView];
        }
        if (view.frame.origin.x <= 0) {
            [self.coverView stopImageSwitch];
        }
        
        initialized = YES;
        
        _orignFrame = view.frame;
        view.layer.shadowColor=[UIColor blackColor].CGColor;
        view.layer.shadowOffset = CGSizeMake(4, 0);
        view.layer.shadowOpacity = 0.8;
        view.layer.shadowRadius = 3.0;
        CGPathRef path = [UIBezierPath bezierPathWithRect:CGRectMake(view.bounds.size.width-2,
                                                                     0,
                                                                     2,
                                                                     view.bounds.size.height)].CGPath;
        [view.layer setShadowPath:path];
        
    } else if ([gestureRecognizer state] == UIGestureRecognizerStateBegan ||
               [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        
        CGRect frame = view.frame;
        frame.origin.x += translation.x;
        if (frame.origin.x > 0) {
            frame.origin.x = 0;
        } else if (frame.origin.x < -self.view.bounds.size.width) {
            frame.origin.x = -self.view.bounds.size.width;
        }
        view.frame = frame;
        
        [gestureRecognizer setTranslation:CGPointZero inView:self.view];
        
    } else if (gestureRecognizer.state == UIGestureRecognizerStateEnded ||
               gestureRecognizer.state == UIGestureRecognizerStateRecognized ||
               gestureRecognizer.state == UIGestureRecognizerStateCancelled ||
               gestureRecognizer.state == UIGestureRecognizerStateFailed) {
        
        CGRect frame = view.frame;
        CGFloat deltaX = frame.origin.x - _orignFrame.origin.x;
        if (deltaX != 0) {
            if (fabs(deltaX)/self.view.bounds.size.width > (deltaX>0?0.3:0.1)) {
                frame.origin.x = deltaX>0?0:-self.view.bounds.size.width;
            } else {
                frame.origin.x = deltaX>0?-self.view.bounds.size.width:0;
            }
        }
        
        [UIView animateWithDuration:0.2f delay:0.0f options:animationOptionsWithCurve(UIViewAnimationCurveEaseIn)
                         animations:^{
                             view.frame = frame;
                         }
                         completion:^(BOOL finished) {
                             view.layer.shadowOffset = CGSizeMake(0, 0);
                             view.layer.shadowOpacity = 0;
                             if (view.frame.origin.x <0) {
                                 [self.coverView removeFromSuperview];
                                 [self.sourceView sourceViewDidAppear];
                                 
                                 //                                 [self.viewStack removeObject:self.coverView];
                             } else {
                                 [self.sourceView sourceviewWillDisappear];
                                 [self.coverView startImageSwitch];
                             }
                         }];
        initialized = NO;
    }
}

#pragma mark - UIGestureRecognizer Delegate method
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    
    if ([otherGestureRecognizer.view isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollView = (UIScrollView *)otherGestureRecognizer.view;
        if (scrollView.contentOffset.x <= 0) {
            return YES;
        }
    }
    
    return NO;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    //    if (self.sourceView.fingerAdView &&
    //        [touch.view isDescendantOfView:self.sourceView.fingerAdView]) {
    //        return NO;
    //    }
    return YES;
}

#pragma mark

- (CoverView *)coverView{
    if (!_coverView) {
        _coverView = [[CoverView alloc] initWithFrame:self.view.bounds];
        _coverView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    }
    return _coverView;
}

#pragma mark - getter method
- (UIImageView *)bgImageView{
    if (!_bgImageView) {
        _bgImageView  = [[UIImageView alloc] initWithFrame:self.view.bounds];
        _bgImageView.autoresizingMask = UIViewContentModeScaleAspectFill;
        _bgImageView.backgroundColor = [UIColor clearColor];
        _bgImageView.clipsToBounds = YES;
    }
    return _bgImageView;
}
- (SourceView *)sourceView{
    if (!_sourceView) {
        CGFloat  h = [UIScreen mainScreen].bounds.size.height-20;
        _sourceView = [[SourceView alloc] initWithFrame:CGRectMake(0,
                                                                   CGRectGetHeight(self.view.frame)-h,
                                                                   CGRectGetWidth(self.view.frame),
                                                                   h)];
        _sourceView.backgroundColor = [UIColor clearColor];
        _sourceView.delegate = self;
        [self.view addSubview:_sourceView];
    }
    return _sourceView;
}

@end
